package com.trkj.share;

import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.shamanland.fonticon.FontIconDrawable;
import com.trkj.base.BaseActivity;
import com.trkj.base.Constants;
import com.trkj.base.OnResponseResultListener;
import com.trkj.base.newwork.ProgressBarPostDataFromRemote;
import com.trkj.base.utils.AndroidSystem;
import com.trkj.taoruiyun.R;

/**
 * Created by LiZanhong on 2015/06/29.
 */
public class SearchActivity extends BaseActivity implements ListView.OnItemClickListener{
    public static final String ACTION = "com.trkj.share.SearchActivity";
    private JSONArray data = new JSONArray();
    private BitmapUtils bitmapUtils;

    @ViewInject(R.id.list)
    private ListView listView;

    @ViewInject(R.id.keyword)
    private SearchView keyword;

    @Override
    protected String getCustomerTitle() {
        return "搜索";
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        long articleId = parent.getAdapter().getItemId(position);
        Intent intent = new Intent(ArticleDetailActivity.ACTION);
        intent.putExtra("articleId", articleId);
        startActivity(intent);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.activity_search);
        ViewUtils.inject(this);
        bitmapUtils = new BitmapUtils(this);
        listView.setOnItemClickListener(this);
        final TextView header = addListViewHeader();
        modifySearchStyle();

        SearchView sv = (SearchView) findViewById(R.id.keyword);
        sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                final ProgressBarPostDataFromRemote dataFromRemote =
                        new ProgressBarPostDataFromRemote(SearchActivity.this);
                dataFromRemote.setResponseResultListener(new OnResponseResultListener() {
                    @Override
                    public void onResponseResult(String result) {
                        JSONObject jsonObject = JSON.parseObject(result);
                        if (jsonObject.getBoolean("success") == false
                                || jsonObject.getJSONArray("data").size() == 0) {
                            data = new JSONArray();
                        } else {
                            data = jsonObject.getJSONArray("data");

                        }
                        header.setText("为您搜索到" + data.size() + "条记录");
                        listView.setAdapter(new ArticleAdapter());
                        listView.requestFocus();
                        //隐藏输入法
                        AndroidSystem.toggleInputMethod(SearchActivity.this);
                    }
                });

                String params = "keyword=" + query + "&rows=50";
                dataFromRemote.execute(Constants.ApiUrl.SEARCH, params);
                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                return false;
            }
        });

    }

    /**
     * 修改搜索框的样式
     */
    private void modifySearchStyle() {
        int id = keyword.getContext().getResources()
                .getIdentifier("android:id/search_src_text", null, null);
        TextView tvKeyWork = (TextView) keyword.findViewById(id);
        tvKeyWork.setTextSize(16);
        tvKeyWork.setHintTextColor(R.color.normal_unselected);
    }

    /**
     * 添加ListView的头
     * @return
     */
    private TextView addListViewHeader() {
        final TextView header = new TextView(this);
        header.setTextSize(12);
        header.setPadding(30, 10, 25, 10);
        listView.addHeaderView(header);
        return header;
    }

    class ArticleAdapter extends BaseAdapter {
        @Override
        public int getItemViewType(int position) {
            JSONObject object = data.getJSONObject(position);
            if(TextUtils.isEmpty(object.getString("cover"))){
                return 0; //不带图片
            }else{
                return 1; //带图片
            }
        }

        @Override
        public int getViewTypeCount() {
            return 2;
        }

        @Override
        public int getCount() {
            return data.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return data.getJSONObject(position).getIntValue("article_id");
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            final ViewHolder viewHolder;
            if (convertView == null) {

                if(getItemViewType(position) == 1){
                    //////////////带图片的/////////
                    convertView = LayoutInflater.from(SearchActivity.this).inflate(
                            R.layout.fragment_share_item_image, null);
                }else {
                    //////////////不带图片的/////////
                    convertView = LayoutInflater.from(SearchActivity.this).inflate(
                            R.layout.fragment_share_item, null);
                }

                viewHolder = new ViewHolder();
                viewHolder.articleTitle = (TextView) convertView.findViewById(R.id.article_title);
                viewHolder.shareDate = (TextView) convertView.findViewById(R.id.share_date);
                viewHolder.shareAuthor = (TextView) convertView.findViewById(R.id.share_author);
                viewHolder.shareReason = (TextView) convertView.findViewById(R.id.share_reason);

                viewHolder.rightArrow = (ImageView) convertView.findViewById(R.id.right_arrow);

                //////////////带图片的/////////
                if(getItemViewType(position) == 1){
                    viewHolder.conver = (ImageView) convertView.findViewById(R.id.conver);
                }

                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }

            viewHolder.articleTitle.setText(Html.fromHtml(
                    data.getJSONObject(position).getString("title_")));
            viewHolder.shareDate.setText(
                    data.getJSONObject(position).getString("date_").substring(0, 11));

            String author = data.getJSONObject(position).getString("author");
            if (TextUtils.isEmpty(author)) {
                viewHolder.shareAuthor.setVisibility(View.GONE);
            } else {
                viewHolder.shareAuthor.setVisibility(View.VISIBLE);
                viewHolder.shareAuthor.setText(author);
            }
            viewHolder.rightArrow.setImageDrawable(
                    FontIconDrawable.inflate(SearchActivity.this, R.xml.right_arrow));

            String reason = data.getJSONObject(position).getString("reason_");
            if (TextUtils.isEmpty(reason)) {
                viewHolder.shareReason.setVisibility(View.GONE);
            } else {
                viewHolder.shareReason.setVisibility(View.VISIBLE);
                viewHolder.shareReason.setText(reason);
            }

            //////////////带图片的/////////
            if(getItemViewType(position) == 1){
                String image = data.getJSONObject(position).getString("cover");
                if(!image.startsWith("http")){
                    image = "http://gson.cn" + image;
                }
                bitmapUtils.display(viewHolder.conver, image);
            }

            return convertView;
        }

        class ViewHolder {
            TextView articleTitle;
            ImageView rightArrow;
            TextView shareDate;
            TextView shareAuthor;
            TextView shareReason;
            ImageView conver;
        }
    }
}
